<template>
    <div class="site-info-page" v-loading="loading || submitLoading">
       <el-form
            class="info-setting-form"
            ref="formRef" 
            :model="formData" 
            :rules="rules"
            label-width="200px">
            <el-form-item prop="brand" label="品牌key：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.brand"
                    maxlength="100"
                    placeholder="请输入品牌key"
                    :disabled="!!brand"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="domain" label="站点域名：">
                <el-row class="input-w510">
                    <el-col :span="13">
                        <el-input
                            v-model.trim="formData.domain.domainKey"
                            maxlength="20"
                            placeholder="请输入域名关键词"
                            clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="10" :offset="1">
                        <el-input
                            v-model.trim="formData.domain.domainBase"
                            maxlength="40"
                            placeholder="请输入域名"
                            clearable>
                        </el-input>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item prop="brandDescription" label="站点介绍：">
                <el-input
                    class="input-w510"
                    type="textarea"
                    :rows="3"
                    v-model.trim="formData.brandDescription"
                    maxlength="200"
                    placeholder="请输入站点介绍"
                    clearable>
                </el-input>
            </el-form-item>
            <el-divider></el-divider>
            <!-- 顶部配置开始 -->
            <div class="section-label">顶部配置</div>
            <el-form-item prop="indexNavLogoUrl" label="首页导航LOGO：">
                <UploadSingleImg
                    :file-item="formData.indexNavLogoUrl" 
                    :check-config="{
                        checkType: 'length',
                        checkValue: 1,
                        tips: '（建议尺寸：82px * 30px）'
                    }"
                    @update:file-item="updateFile('indexNavLogoUrl', $event)"/>
            </el-form-item>
            <el-form-item prop="favicon" label="网页标题栏LOGO：">
                <UploadSingleImg
                    :file-item="formData.favicon" 
                    :check-config="{
                        checkType: 'length',
                        checkValue: 1,
                        tips: '（建议尺寸：32px * 32px）'
                    }"
                    @update:file-item="updateFile('favicon', $event)"/>
            </el-form-item>
            <el-form-item prop="otherNavLogoUrl" label="二级页及其他导航LOGO：">
                <UploadSingleImg
                    :file-item="formData.otherNavLogoUrl" 
                    :check-config="{
                        checkType: 'length',
                        checkValue: 1,
                        tips: '（建议尺寸：60px * 60px）'
                    }"
                    @update:file-item="updateFile('otherNavLogoUrl', $event)"/>
            </el-form-item>
            <el-form-item prop="siteName" label="站点名称：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.siteName"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入站点名称"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="webTitle" label="网页标题：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.webTitle"
                    maxlength="200"
                    placeholder="请输入网页标题"
                    clearable>
                </el-input>
            </el-form-item>
            <!-- 顶部配置结束 -->
            <el-divider></el-divider>
            <!-- 底部配置开始 -->
            <div class="section-label">底部配置</div>
            <el-form-item prop="copyright" label="版权信息：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.copyright"
                    maxlength="200"
                    placeholder="请输入版权信息"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="recordNumber" label="ICP备案号：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.recordNumber"
                    maxlength="200"
                    placeholder="请输入ICP备案号"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="technicalSupport" label="技术支持：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.technicalSupport"
                    maxlength="200"
                    placeholder="请输入技术支持"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="publicRecord" label="公网备案号：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.publicRecord.recordCode"
                    maxlength="200"
                    placeholder="请输入公网备案号"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="recordUrl" label="备案url：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.publicRecord.recordUrl"
                    maxlength="200"
                    placeholder="请输入备案url"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="privacyClauseWeb" label="隐私条款：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.privacyClauseWeb"
                    maxlength="200"
                    placeholder="请输入隐私条款"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="userAgreementWeb" label="用户协议：">
                <el-input
                    class="input-w510"
                    v-model.trim="formData.userAgreementWeb"
                    maxlength="200"
                    placeholder="请输入用户协议"
                    clearable>
                </el-input>
            </el-form-item>
            <el-form-item prop="footerLogoUrl" label="页脚LOGO：">
                <UploadSingleImg
                    :file-item="formData.footerLogoUrl" 
                    :check-config="{
                        checkType: 'length',
                        checkValue: 1,
                        tips: '（建议尺寸：149px * 22px）'
                    }"
                    @update:file-item="updateFile('footerLogoUrl', $event)"/>
            </el-form-item>
            <el-form-item prop="otherFooters" label="页脚信息：">
                <div>
                    <div class="info-tips">最多添加6个</div>
                    <FooterList
                        ref="footerInfoRef"
                        :footer-list="formData.otherFooters"
                        @update:footer-list="updateFile('otherFooters', $event)"/>
                </div>
            </el-form-item>
            <!-- 底部配置结束 -->
            <el-divider></el-divider>
            <!-- 侧边栏配置开始 -->
            <div class="section-label">侧边栏配置</div>
            <div class="flex-top">
                <el-form-item prop="questionsEnabled" label="" label-width="100px">
                    <el-checkbox v-model="formData.sidebarConfig.questionsEnabled">开通常见问答</el-checkbox>
                </el-form-item>
                <el-form-item class="ml-20" prop="questionsUrl" label="" label-width="0px">
                    <el-input
                        class="input-w400"
                        v-model="formData.sidebarConfig.questionsUrl"
                        maxlength="200"
                        placeholder="这里是一个SRT统一的常见问答地址"
                        clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="ml-20" prop="questionsCustomName" label="" label-width="0px">
                    <el-input
                        class="input-w400"
                        v-model="formData.sidebarConfig.questionsCustomName"
                        maxlength="20"
                        placeholder="“常见问答”在前台展示的自定义名称"
                        clearable>
                    </el-input>
                </el-form-item>
            </div>
            <el-form-item prop="feedbackEnabled" label="" label-width="100px">
                <el-checkbox v-model="formData.sidebarConfig.feedbackEnabled">开通意见反馈</el-checkbox>
            </el-form-item>
            <div class="flex-top">
                <el-form-item prop="appQrCodeEnabled" label="" label-width="100px">
                    <el-checkbox v-model="formData.sidebarConfig.appQrCodeEnabled">配置APP下载二维码</el-checkbox>
                </el-form-item>
                <div>
                    <el-form-item prop="sideAppLogo" label="" label-width="0px">
                        <UploadSingleImg
                            class="ml-20"
                            ref="appLogoRef"
                            :file-item="formData.sidebarConfig.appLogo" 
                            :check-config="{
                                checkType: 'length',
                                checkValue: 1,
                                tips: 'pc页面侧边栏展示app的logo和app下载二维码'
                            }"
                            btn-text="上传appLogo"
                            @update:file-item="updateFile('sidebarConfig.appLogo', $event)"/>
                        <!-- <div class="ml-20">
                            <div>

                            </div>
                            <div class="mt-20">
                            </div>
                        </div> -->
                    </el-form-item>
                    <el-form-item prop="sideAppQrCodeUrl" label="" label-width="0px">
                        <UploadSingleImg
                            class="ml-20"
                            ref="appQrCodeUrlRef"
                            :file-item="formData.sidebarConfig.appQrCodeUrl" 
                            :check-config="{
                                checkType: 'length',
                                checkValue: 1,
                                tips: ' '
                            }"
                            btn-text="上传二维码"
                            @update:file-item="updateFile('sidebarConfig.appQrCodeUrl', $event)"/>
                    </el-form-item>
                </div>
            </div>
            <!-- 侧边栏配置结束 -->
            <el-divider></el-divider>
            <!-- app配置开始 -->
            <div class="section-label">app配置</div>
            <el-form-item prop="appEnabled" label="是否开通app：">
                <el-radio-group v-model="formData.appEnabled">
                    <el-radio :label="true" size="large">是</el-radio>
                    <el-radio :label="false" size="large">否</el-radio>
                </el-radio-group>
                <span class="info-tips">开通后，在app看到站点入口，可以进入站点。</span>
            </el-form-item>
            <el-form-item prop="appLogo" label="app logo：">
                <UploadSingleImg
                    :file-item="formData.appLogo" 
                    :check-config="{
                        checkType: 'length',
                        checkValue: 1,
                        tips: 'app站点入口上的logo图'
                    }"
                    btn-text="上传图片"
                    @update:file-item="updateFile('appLogo', $event)"/>
            </el-form-item>
            <!-- app配置结束 -->
            <!-- <el-form-item label="" label-width="200px">
                <div class="mt-20">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submit" :loading="submitLoading">保存</el-button>
                </div>
            </el-form-item> -->
        </el-form>
        <div class="common-save mt-20">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit" :loading="submitLoading">保存</el-button>
        </div>
    </div>
</template>

<script setup>
// 站点信息设置页面
import UploadSingleImg from '@/components/upload/upload-single-img.vue';
import FooterList from './footer-list.vue';
import { ref, reactive, onMounted, defineProps, watch, defineEmits } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import { validateUrl } from '@/lib/tools.js';
import { pageJump } from '@/global/location-transfer';
import { useMessage } from '@/hooks/useMessage.js';

const store = useStore();

const route = useRoute();

const {messageSuccess, messageError} = useMessage();

const props = defineProps({
    currentTab: {
        type: String,
        default: ''
    },
    institutionInfo: {
        type: Object,
        default: () => {}
    }
});

const emit = defineEmits(['updateInstitution', 'updateBrandId']);

// 表单ref
let formRef = ref(null);

// 其他底部信息Ref
let footerInfoRef = ref(null);

// 侧边栏appLogoRef
let appLogoRef = ref(null);

// 侧边栏app地址Ref
let appQrCodeUrlRef = ref(null);

// 默认表单信息表单信息
let defaultFormData = reactive({
    brand: '', // 品牌key
    domain: {
        domainBase: '.3ren.cn', // 域名
        domainKey: '' // 域名关键词
    },
    brandDescription: '', // 站点介绍
    indexNavLogoUrl: 'https://d1.3ren.cn/static/front-res/grain-wand-web/nav-logo1.png', // 首页导航LOGO
    favicon: 'https://d1.3ren.cn/static/front-res/grain-wand-web/web-logo.png', // 网页标题栏LOGO
    otherNavLogoUrl: 'https://d1.3ren.cn/static/front-res/grain-wand-web/web-logo.png', // 二级页及其他导航logo
    siteName: '', // 站点名称
    webTitle: '尚睿通', // 网页标题
    copyright: 'Copyright©2019 www.3ren.cn 中国教师研修网', // 版权信息
    recordNumber: '京ICP备06018303号-13', // ICP备案号
    technicalSupport: '北京尚睿通教育科技股份有限公司', // 技术支持
    publicRecord: {
        recordCode: '京公网安备 11010202008206号', // 公网备案号
        recordUrl: 'http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010202008206' // 备案url
    },
    footerLogoUrl: 'https://d1.3ren.cn/static/front-res/grain-wand-web/footer-logo1.png', // 页脚LOGO
    privacyClauseWeb: '', // 隐私条款
    userAgreementWeb: '', // 用户协议
    otherFooters: [], // 页脚样式
    sidebarConfig: {
        questionsEnabled: '', // 开通常见问答
        questionsUrl: '', // 常见问答地址
        questionsCustomName: '', // 常见问答自定义名称
        feedbackEnabled: '', // 开通意见反馈
        appQrCodeEnabled: '', // 配置APP下载二维码
        appLogo: '', // applogo
        appQrCodeUrl: '' // app地址
    },
    appEnabled: '', // 是否开通app
    appLogo: '', // app logo
    version: 'v2', // 版本 默认v1 睿云2.0用v2
    domainBase: '.3ren.cn', // 域名
    domainKey: '', // 域名关键词
    brandName: '',
    simpleNavLogoUrl: '', // 不填
    tenant: '',
    brandType: '',
    // groups: [], // 品牌分组
    groupIds: [], // 品牌分组ID，无分组不传
    scopeAreas: [], // 区域性业务地区编码
    businessScopeCode: '' // 业务范围
});

// 表单信息
let formData = reactive({
    ...defaultFormData
});

// 品牌
let brand = ref('');

let loading = ref(false);

let submitLoading = ref(false);

// 品牌key校验 
const checkBrand = (rule, value, callback) => {
    if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
            callback(new Error('不能输入汉字'))
        } else {
            callback()
        }
    } else {
        callback(new Error('请输入品牌key'))
    }
}

// 域名校验
const domainValid = (rule, value, callback) => {
    if (value.domainBase && value.domainKey) {
        if (/[\u4E00-\u9FA5]/g.test(value.domainBase) || /[\u4E00-\u9FA5]/g.test(value.domainKey)) {
            callback(new Error('不能输入汉字'))
        } else {
            callback()
        }
    } else {
        callback(new Error('请输入站点域名'))
    }
}

// 校验备案url链接地址是否正确
const checkRecordUrl = (rule, value, callback) => {
    validateUrl(rule, formData.publicRecord.recordUrl, callback);
};

// 校验问答地址url
const checkQuestionsUrl = (rule, value, callback) => {
    if (formData.sidebarConfig.questionsEnabled) {
        rule.required = true;
    }
    validateUrl(rule, formData.sidebarConfig.questionsUrl, callback);
};

// 校验隐私条款url
const checkPrivacyClauseWeb = (rule, value, callback) => {
    validateUrl(rule, formData.privacyClauseWeb, callback);
};

// 校验用户协议url
const checkUserAgreementWeb = (rule, value, callback) => {
    validateUrl(rule, formData.userAgreementWeb, callback);
};

// 校验侧边栏app logo
const checkSideAppLogo = (rule, value, callback) => {
    if (formData.sidebarConfig.appQrCodeEnabled && !formData.sidebarConfig.appLogo) {
        callback(new Error('选中后该项为必选项'));
    } else {
        callback();
    }
};

// 校验侧边栏app地址
const checkSideAppQrCodeUrl = (rule, value, callback) => {
    if (formData.sidebarConfig.appQrCodeEnabled && !formData.sidebarConfig.appQrCodeUrl) {
        callback(new Error('选中后该项为必选项'));
    } else {
        callback();
    }
};

// 校验appLogo
const checkAppLogo = (rule, value, callback) => {
    if (formData.appEnabled && !value) {
        rules.appLogo[0].required = true;
        callback(new Error('确认开通app，此项为必选项'));
    } else {
        rules.appLogo[0].required = false;
        callback();
    }
}

// 表单校验规则
const rules = reactive({
    brand: [{ required: true, validator: checkBrand, trigger: 'blur' }],
    domain: [{ required: true, validator: domainValid, trigger: 'blur' }],
    indexNavLogoUrl: [{ required: true, message: '请选择首页导航Logo', trigger: 'change' }],
    favicon: [{ required: true, message: '请选择网页标题栏Logo', trigger: 'change' }],
    otherNavLogoUrl: [{ required: true, message: '请选择二级页及其他导航LOGO', trigger: 'change' }],
    siteName: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
    webTitle: [{ required: true, message: '请输入网页标题', trigger: 'blur' }],
    copyright: [{ required: true, message: '请输入版权信息', trigger: 'blur' }],
    recordNumber: [{ required: true, message: '请输入ICP备案号', trigger: 'blur' }],
    technicalSupport: [{ required: true, message: '请输入技术支持', trigger: 'blur' }],
    publicRecord: [{
        required: true,
        validator: (rule, value, callback) => {
                if (!value.recordCode) {
                    callback(new Error('请输入公网备案号'));
                } else {
                    callback();
                }
            },
        trigger: 'blur'
    }],
    footerLogoUrl: [{ required: true, message: '请上传页脚Logo', trigger: 'change' }],
    appEnabled: [{ required: true, message: '请选择是否开通app', trigger: 'change' }],
    appLogo: [{ required: false, validator: checkAppLogo, trigger: 'change' }],
    recordUrl: [{ required: false, validator: checkRecordUrl, trigger: 'blur' }],
    questionsUrl: [{ required: false, validator: checkQuestionsUrl, trigger: 'blur' }],
    privacyClauseWeb: [{ required: false, validator: checkPrivacyClauseWeb, trigger: 'blur' }],
    userAgreementWeb: [{ required: false, validator: checkUserAgreementWeb, trigger: 'blur' }],
    sideAppLogo: [{ required: false, validator: checkSideAppLogo, trigger: 'change' }],
    sideAppQrCodeUrl: [{ required: false, validator: checkSideAppQrCodeUrl, trigger: 'change' }]
})

// 更新表单数据
const updateFile = (item, $event) => {
    let arr = item.split('.');
    if (arr.length === 2) {
        formData[arr[0]][arr[1]] = $event;
    } else {
        formData[item] = $event;
    }
}


const cancel = () => {
    pageJump({ name: 'siteList' });
}

const submit = async () => {
    let result = await footerInfoRef.value.checkForm();
    formRef.value.validate(valid => {
        if (!valid || !result) {
            messageError('请检查必填项');
            return;
        }
		saveSiteRelationship();
    })
}

// 获取站点基础信息
const getBrandInfo = (type = false) => {
    if (!brand.value) {
        formRef.value.clearValidate();
        return;
    }

    // 清空默认数据

    loading.value = true;
    store.dispatch('proxyAction', {
        name: 'getBrandInfo',
        queries: {
            brand: brand.value
        }
    }).then((res) => {
       let data = res.data
        if(!data) {
            return;
        }
        Object.assign(formData, 
        {
            ...data,
            ...data.brandConfig,
            brand: brand.value,
            webTitle: data.brandConfig && data.brandConfig.webTitle || formData.webTitle,
            domain: {
                domainBase: data.domainBase || defaultFormData.domainBase, // 域名
                domainKey: data.domainKey || defaultFormData.domainKey // 域名关键词
            }
        });
        if (data.groups && data.groups.length) {
            data.groupIds = []
            data.groups.forEach(item => {
                formData.groupIds.push(item.groupId)
            })
        }
        if (data.brandConfig && data.brandConfig.businessScope && data.brandConfig.businessScope.scope) {
            formData.businessScopeCode = data.brandConfig.businessScope.scope
        } else {
            formData.businessScopeCode = ''
        }
        if (data.brandConfig && data.brandConfig.businessScope && data.brandConfig.businessScope.scopeAreas) {
            formData.scopeAreas.push(data.brandConfig.businessScope.scopeAreas[0].provinceCode);
            formData.scopeAreas.push(data.brandConfig.businessScope.scopeAreas[0].cityCode);
        } else {
            formData.scopeAreas = [];
        }
        rules.appLogo[0].required = !!formData.appEnabled;
        formRef.value.clearValidate();
        if(type){
            emit('updateInstitution', formData.brandId);
        }else {
            emit('updateBrandId', formData.brandId);
        }
    }).finally(() => {
        loading.value = false;
    })
}

// 初始化站点信息
const initBrand = () => {
    formRef.value.resetFields();
    appLogoRef.value.clearFormItem();
    appQrCodeUrlRef.value.clearFormItem();
    formData.otherFooters = [];
    brand.value = '';
    let data = props.institutionInfo;
    if (!data) {
        return;
    }
    brand.value = data.siteBrand || ''
    formData.tenant = data.dtTenant || '';
    formData.brand = brand.value;
    formData.webTitle = data.institutionName;
    formData.brandName = data.institutionName;
    if (!brand.value) {
        formData.siteName = data.siteName;
    }
    getBrandInfo();
}

// 保存组织站点关系(保存站点信息前先调用这个接口)
const saveSiteRelationship = () => {
    submitLoading.value = true;
    store.dispatch('proxyAction', {
        name: 'saveSiteRelationship',
        data: {
            id: route.query.id, // 组织id
            siteBrand: formData.brand, // 品牌key
            siteName: formData.siteName // 站点名称
        }
    }).then((res) => {
        brand.value = formData.brand;
		saveSiteBaseInfo();
    }).catch((err) => {
        submitLoading.value = false;
        console.log(err);
    })
}

// 保存站点基础信息
const saveSiteBaseInfo = () => {
    let tempFooter = [];
    formData.otherFooters.forEach((item, index) => {
        if (item.footerName && item.footerValue) {
            tempFooter.push({...item, sort: index + 1});
        }
    })
    store.dispatch('proxyAction', {
        name: 'saveSiteBaseInfo',
        data: {
            ...formData,
            ...formData.domain,
            otherFooters: tempFooter,
            brandState: 1
        }
    }).then((res) => {
        messageSuccess(res.data);
       getBrandInfo(true);
    }).catch((err) => {
        submitLoading.value = false;
        // 品牌已存在
        if (err.status && err.status.code && err.status.code === 3018011) {
            formData.brand = '';
            brand.value = '';
        }
    }).finally(() => {
        submitLoading.value = false;
    })
}
onMounted(() => {
    // initBrand();
})

watch(() => props.currentTab, (newVal) => {
    if (newVal === 'information') {
        initBrand();
    }
})

</script>

<style lang="scss" scoped>
.site-info-page {
    .section-label {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 28px;
            background-color: $--color-blue;
            margin-right: 15px;
        }
    }
    .info-setting-form {
        height: calc(100vh - 284px);
        overflow-y: auto;
        .input-w510 {
            width: 510px;
        }
        .input-w400 {
            width: 400px;
        }
        .ml-20 {
            margin-left: 20px;
        }
        .info-tips {
            padding-left: 8px;
            color: var( --main-text-tip);
            font-size: 12px;
        }
        .mt-20 {
            margin-top: 20px;
        }
        .flex-top {
            display: flex;
            justify-content: flex-start;
            align-items: flex-start;
        }
    }
    .common-save {
        text-align: center;
        padding-top: 20px;
        border-top: 1px solid #eeeeee;
    }
}
</style>